const cloud = require('wx-server-sdk')
const request = require('request')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const APPID = 'wxb6e63fcd64a61d40'
const APPSECRET = '70b886b9246542af7636ca397879de68'

exports.main = async (event, context) => {
  const code = event.code
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code`

  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'GET',
      json: true
    }, function(error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log('session_key:', body.session_key)
        console.log('openid:', body.openid)
        resolve({
          openid: body.openid,
          session_key: body.session_key
        })
      } else {
        console.error('请求失败:', error)
        reject({ error: '请求失败' })
      }
    })
  })
}
